<template>
    <div>
        <app-head :nickname-value="userInfo.nickname"
                  :avatarValue="userInfo.avatar"></app-head>
        <app-body>
            <div v-show="!eidtAddress">
                <div class="user-info-container">
                    <div class="user-info-details">

                        <el-upload
                                action="http://10.192.149.34:30090/user/upload/image"
                                :headers="authHeaders"
                                :on-success="fileHandleSuccess"
                                :file-list="imgFileList"
                                accept="image/*"
                        >
                            <el-image
                                    style="width: 120px; height: 120px;border-radius: 10px;"
                                    :src="userInfo.avatar"
                                    fit="contain"></el-image>
                        </el-upload>
                        <div class="user-info-details-text">
                            <div class="user-info-details-text-nickname">{{userInfo.nickname}}</div>
                            <div class="user-info-details-text-time">{{userInfo.signInTime}} 加入平台</div>
                            <div class="user-info-details-text-edit">
                                <el-button type="primary" plain @click="userInfoDialogVisible = true">编辑个人信息</el-button>
                                <el-button type="primary" plain @click="eidtAddress=true">编辑收货地址</el-button>
                            </div>
                            <el-dialog
                                    @close="finishEdit"
                                    title="编辑个人信息"
                                    :visible.sync="userInfoDialogVisible"
                                    width="400px">
                                <div class="edit-tip">昵称</div>
                                <el-input
                                        v-model="userInfo.nickname"
                                        :disabled="notUserNicknameEdit"
                                        @change="saveUserNickname">
                                    <el-button slot="append" type="warning" icon="el-icon-edit"
                                               @click="notUserNicknameEdit = false">编辑
                                    </el-button>
                                </el-input>

                                <div v-if="userPasswordEdit">
                                    <div class="edit-tip">原密码</div>
                                    <el-input v-model="userPassword1" show-password></el-input>
                                    <div class="edit-tip">新密码</div>
                                    <el-input v-model="userPassword2" show-password></el-input>
                                    <div class="edit-tip">确认新密码</div>
                                    <el-input v-model="userPassword3" show-password></el-input>
                                    <div class="edit-tip"></div>
                                    <el-button @click="savePassword" plain>确认修改</el-button>
                                </div>
                                <div v-else>
                                    <div class="edit-tip">密码</div>
                                    <el-input
                                            value="123456"
                                            :disabled="true"
                                            show-password>
                                        <el-button slot="append" type="warning" icon="el-icon-edit"
                                                   @click="userPasswordEdit = true">编辑
                                        </el-button>
                                    </el-input>
                                </div>
                                <span slot="footer" class="dialog-footer">
                                <el-button @click="userInfoDialogVisible=false">完成</el-button>
                            </span>
                            </el-dialog>
                        </div>
                    </div>
                    <div class="user-info-splace">
                    </div>
                </div>
                <div class="idle-container">
                    <!-- 顶部标签页 -->
                    <el-tabs v-model="activeName" @tab-click="handleClick">
                        <el-tab-pane label="我发布的" name="1"></el-tab-pane>
                        <el-tab-pane label="我下架的" name="2"></el-tab-pane>
                        <el-tab-pane label="我收藏的" name="3"></el-tab-pane>
                        <el-tab-pane label="我卖出的" name="4"></el-tab-pane>
                        <el-tab-pane label="我买到的" name="5"></el-tab-pane>
                        <el-tab-pane label="我的关注" name="6"></el-tab-pane>
                        <el-tab-pane label="我的粉丝" name="7"></el-tab-pane>
                    </el-tabs>
                    <!-- 列表展示区域 -->
                    <div class="idle-container-list">
                        <div v-for="(item,index) in dataList[activeName-1]" :key="item.id" class="idle-container-list-item">
                            <!-- 关注粉丝-->
                            <template v-if="activeName === '6' || activeName === '7'">
                                <div class="user-card">
                                    <!-- 左侧：头像 + 昵称 -->
                                    <div class="user-card-left">
                                        <el-image :src="item.imgUrl" style="width: 50px; height: 50px; border-radius: 50%;" />
                                        <div class="nickname">{{ item.idleName }}</div>
                                    </div>

                                    <!-- 右侧：按钮 -->
                                    <div class="user-card-right">
                                        <!-- 取消关注（关注列表） -->
                                        <!-- 取消关注（关注列表） -->
                                        <el-button
                                            v-if="activeName === '6'"
                                            size="mini"
                                            type="danger"
                                            @click="unfollowUser(item.userId)"
                                        >
                                            取消关注
                                        </el-button>


                                        <!-- 回关或已关注（粉丝列表） -->
                                        <template v-if="activeName === '7'">
                                            <el-button
                                                v-if="!item.isFollowed"
                                                size="mini"
                                                type="primary"
                                                @click="followBack(item.userId)"
                                            >
                                                回关
                                            </el-button>
                                            <el-button
                                                v-else
                                                size="mini"
                                                type="success"
                                                plain
                                                disabled
                                                class="followed-button"
                                            >
                                                已关注
                                            </el-button>
                                        </template>
                                    </div>
                                </div>
                            </template>

                            <!-- 商品卡片区域 -->
                            <template v-else>
                                <div class="idle-container-list-item-detile" @click="toDetails(activeName,item)">
                                    <el-image style="width: 120px; height: 120px; border-radius: 8px;" :src="item.imgUrl || (item.images ? item.images.split(',')[0] : '')"


                                              fit="cover">
                                        <!-- 如果加载失败显示无图 -->
                                        <div slot="error" class="image-slot">
                                            <i class="el-icon-picture-outline"></i>
                                            <span class="no-image-text">暂无图片</span>
                                        </div>
                                    </el-image>
                                    <div class="idle-container-list-item-text">
                                        <!-- 商品名称 -->
                                        <div class="idle-container-list-title">
                                            {{item.idleName || item.productName}}
                                            <el-tag v-if="item.statusSold === 'ON_SALE'" type="success" size="mini">在售</el-tag>
                                            <el-tag v-else-if="item.statusSold === 'SOLD'" type="info" size="mini">已售出</el-tag>
                                        </div>
                                        <!-- 商品描述 -->
                                        <div class="idle-container-list-idle-details" v-html="item.idleDetails || item.productDescription"></div>
                                        <!-- 发布时间和收藏数 -->
                                        <div class="idle-container-list-idle-time">
                                            <span class="time-text">{{item.timeStr}}</span>
                                            <span class="favorite-count" v-if="item.favoriteCount !== undefined">
                                                <i class="el-icon-star-on"></i>
                                                {{item.favoriteCount}}
                                            </span>
                                        </div>
                                        <!-- 卡片底部 -->
                                        <div class="idle-item-foot">
                                            <div class="idle-price">￥{{item.productPrice}}
                                                {{(activeName=== '4' ||activeName=== '5')?orderStatus[item.orderStatus]:''}}
                                            </div>
                                            <!-- 不同页面显示不同按钮 -->
                                            <div class="operation-buttons">
                                                <template v-if="activeName === '1'">
                                                    <el-button type="danger" size="mini" plain @click.stop="handleDown(item, index)">下架</el-button>
                                                    <el-button type="primary" size="mini" plain @click.stop="editItem(item)">编辑</el-button>
                                                </template>
                                                <template v-else-if="activeName === '3'">
                                                    <el-button type="danger" size="mini" plain @click.stop="handle(activeName,item,index)">
                                                        取消收藏
                                                    </el-button>
                                                </template>
                                                <template v-else-if="activeName !== '4' && activeName !== '5'">
                                                    <el-button type="primary" size="mini" plain @click.stop="handle(activeName,item,index)">
                                                        {{handleName[activeName-1]}}
                                                    </el-button>
                                                </template>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <!-- 空状态显示 -->
                        <el-empty v-if="!dataList[activeName-1] || dataList[activeName-1].length === 0" 
                                 description="暂无数据">
                        </el-empty>
                    </div>
                </div>
            </div>
            <div v-show="eidtAddress" class="address-container">
                <el-page-header class="address-container-back" @back="eidtAddress=false"
                                content="收货地址"></el-page-header>
                <div class="address-container-add">
                    <div class="address-container-add-title">新增收货地址</div>
                    <div class="address-container-add-item">
                        <el-input placeholder="请输入收货人姓名" v-model="addressInfo.consigneeName" maxlength="10"
                                  show-word-limit>
                            <div slot="prepend">收货人姓名</div>
                        </el-input>
                    </div>
                    <div class="address-container-add-item">
                        <el-input placeholder="请输入收货人手机号" v-model="addressInfo.consigneePhone"
                                  onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" maxlength="11" show-word-limit>
                            <div slot="prepend">手机号</div>
                        </el-input>
                    </div>

                    <div class="address-container-add-item">
                        <span class="demonstration">省/市/区</span>
                        <el-cascader
                                :options="options"
                                v-model="selectedOptions"
                                @change="handleAddressChange"
                                :separator="' '"
                        >
                        </el-cascader>
                    </div>
                    <div class="address-container-add-item">
                        <el-input placeholder="请输入详细地址（如道路、门牌号、小区、楼栋号等信息）" v-model="addressInfo.detailAddress"
                                  maxlength="50" show-word-limit>
                            <div slot="prepend">详细地址</div>
                        </el-input>
                    </div>
                    <el-checkbox v-model="addressInfo.defaultFlag">设置为默认地址</el-checkbox>
                    <el-button style="margin-left: 20px;" @click="saveAddress">保存</el-button>
                </div>
                <div class="address-container-list">
                    <div style="color: #409EFF;font-size: 15px;padding-left: 10px;">已有收货地址</div>
                    <el-table
                            stripe
                            :data="addressData"
                            style="width: 100%">
                        <el-table-column
                                prop="consigneeName"
                                label="收货人姓名"
                                width="100">
                        </el-table-column>
                        <el-table-column
                                prop="consigneePhone"
                                label="手机号"
                                width="120">
                        </el-table-column>
                        <el-table-column
                                prop="detailAddressText"
                                label="地址"
                                width="270">
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button
                                        size="mini"
                                        @click="handleEdit(scope.$index, scope.row)">编辑
                                </el-button>
                                <el-button
                                        size="mini"
                                        type="danger"
                                        @click="handleDelete(scope.$index, scope.row)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="是否默认地址" width="110">
                            <template slot-scope="scope">
                                <el-button v-if="!scope.row.defaultFlag"
                                           size="mini"
                                           @click="handleSetDefault(scope.$index, scope.row)">设为默认
                                </el-button>
                                <div v-else style="padding-left: 10px;color: #409EFF;">{{scope.row.defaultAddress}}
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <app-foot></app-foot>
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppHeader.vue';
    import AppBody from '../common/AppPageBody.vue'
    import AppFoot from '../common/AppFoot.vue'
    import options from '../common/country-data.js'

    export default {
        name: "me",
        ref: "me",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        data() {
            return {
                imgFileList: [],
                addressInfo: {
                    consigneeName: '',
                    consigneePhone: '',
                    provinceName: '',
                    cityName: '',
                    regionName: '',
                    detailAddress: '',
                    defaultFlag: false
                },
                activeName: '1',
                //用于根据当前激活的标签页（即 activeName）动态显示每个商品下方操作按钮的名称
                //第一个（"我发布的"）虽然是"下架"，但不会被用到，因为你已经写了独立的两个按钮渲染逻辑
                handleName: ['下架', '重新上架', '取消收藏', '', ''],
                dataList: [
                    [], // 我发布的
                    [], // 我下架的
                    [], // 我收藏的
                    [], // 我卖出的
                    [], // 我买到的
                    [], // 我的关注
                    [], // 我的粉丝
                ],
                orderStatus: ['待付款', '待发货', '待收货', '已完成', '已取消'],
                userInfoDialogVisible: false,
                notUserNicknameEdit: true,
                userPasswordEdit: false,
                userPassword1: '',
                userPassword2: '',
                userPassword3: '',
                eidtAddress: false,
                selectedOptions: [],//存放默认值
                options: options,   //存放城市数据,
                userInfo: {
                    id: "",
                    accountNumber: "",
                    avatar: "",
                    nickname: "",
                    signInTime: "",
                },
                addressData: []
            };
        },
        computed: {
            authHeaders() {
                return {
                    Authorization: `Bearer ${window.localStorage.getItem('token')}`
                };
            }
        },
        mounted() {
            //if (!this.$globalData.userInfo.nickname) {
            this.$api.getUserInfo().then(res => {
                if (res.code === 200) {
                    const raw = res.data;

                    this.userInfo = {
                        id: raw.id,
                        accountNumber: raw.userName,
                        avatar: raw.avatarUrl, // 映射字段名
                        nickname: raw.nickname,
                        signInTime: "", // 接口没有传，你可以自己生成 or 删掉
                    };

                    this.$globalData.userInfo = this.userInfo;
                    localStorage.setItem('userInfo', JSON.stringify(this.userInfo));

                    console.log("✅ 解析后的 userInfo：", this.userInfo);
                }
            })
            //} else {
            //    this.userInfo = this.$globalData.userInfo;
            //    console.log(this.userInfo);
            //}

            this.getAddressData();

            this.getMyPublishItem();//自动加载我的发布页面
            this.getMyOffsaleItem();//自动加载我的下架页面
            this.getMyOrder();
            this.getMySoldIdle();
            this.getMyFavorite();//自动加载我收藏的页面
            this.getMyFollowings();
            this.getMyFollowers();
        },
        methods: {
            //加载已发布的商品
            getMyPublishItem(){
                console.log('开始获取已发布商品列表...');
                this.$api.getMyPublishItem().then(res => {
                    console.log('获取已发布商品响应:', res);
                    if(res.code == 200){
                        console.log('获取成功，数据:', res.data);
                        //响应式触发视图更新
                        this.$set(this.dataList, 0, res.data);
                    }else{
                        console.error('获取失败，错误信息:', res.message);
                        this.$message.error(res.message || "获取失败")
                    }
                }).catch((err) => {
                    console.error('请求失败:', err);
                    this.$message.error('请求失败，请稍后再试');
                });
            },
            //加载已下架的商品
            getMyOffsaleItem() {
                this.$api.getMyOffsaleItem().then(res => {
                    if(res.code == 200){
                        this.$set(this.dataList, 1, res.data);
                    }else{
                        this.$message.error(res.message || "获取失败");
                    }
                }).catch(() => {
                    this.$message.error("请求失败，请稍后再试");
                })
            },
            //下架逻辑
            handleDown(item, index) {
                this.$confirm('确定要下架该商品吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$api.downIdleItem(item.productID).then(res => {
                        if (res.code === 200) {
                            this.$message.success('下架成功！');
                            this.dataList[0].splice(index, 1); // 立即移除该商品
                        } else {
                            this.$message.error('下架失败！' + res.msg);
                        }
                    }).catch(() => {
                        // 用户点击了"取消"
                        this.$message.info('已取消操作');
                    });
                }).catch(() => {
                    // 用户点击了"取消"
                    this.$message.info('已取消操作');
                });
            },
            // 编辑逻辑，跳转到编辑页面,这里不进行任何操作
            editItem(item) {
                this.$router.push({ path: '/edit', query: { productId: item.productID } });
            },
            //每当点击顶部的标签页时自动触发
            //根据当前页激活对应商品信息
            handleClick(tab, event) {
                const tabIndex = this.activeName;
                if (tabIndex === '1') this.getMyPublishItem();
                else if (tabIndex === '2') this.getMyOffsaleItem();
                else if (tabIndex === '3') this.getMyFavorite();
                else if (tabIndex === '4') this.getMySoldIdle();
                else if (tabIndex === '5') this.getMyOrder();
                else if (tabIndex === '6') this.getMyFollowings();
                else if (tabIndex === '7') this.getMyFollowers();
            },
            //根据当前页执行不同操作，如下架，重新上架，取消收藏
            handle(activeName,item,index) {
                console.log(activeName,item,index);
                this.$confirm('是否确认？', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //重新上架逻辑
                    if(activeName=== '2'){
                        this.$api.rePublishItem(item.productID).then(res=>{
                            if(res.code=== 200 ){
                                this.dataList[1].splice(index,1);
                            }else {
                                this.$message.error(res.msg)
                            }
                        });
                    }//取消收藏逻辑
                    else if(activeName=== '3'){
                        console.log('Id:', item.id);
                        this.$api.deleteFavorite(item.id).then(res=>{
                            if(res.code === 200){
                                this.$message({
                                    message: '已取消收藏！',
                                    type: 'success'
                                });
                                this.dataList[2].splice(index,1);
                            }else {
                                this.$message.error(res.message || '取消收藏失败')
                            }
                        }).catch(err => {
                            console.error('取消收藏失败:', err);
                            this.$message.error('网络错误，请稍后重试');
                        });
                    }
                }).catch(() => {
                });
            },
            //点击商品项跳转到商品详情页
            toDetails(activeName, item) {
                console.log('跳转详情页，商品信息：', item);
                
                if (activeName === '4' || activeName === '5') {
                    // 订单相关页面的跳转逻辑
                    this.$router.push({
                        path: '/order',
                        query: {
                            id: item.id
                        }
                    });
                } else {
                    // 商品详情页跳转
                    const productId = item.productID || item.id;
                    if (!productId) {
                        console.error('商品ID不存在:', item);
                        this.$message.error('商品ID不存在');
                        return;
                    }
                    
                    this.$router.push({
                        path: '/details',
                        query: {
                            productId: productId
                        }
                    }).catch(err => {
                        console.error('路由跳转失败:', err);
                        this.$message.error('页面跳转失败，请稍后重试');
                    });
                }
            },
            saveUserNickname() {
                this.notUserNicknameEdit = true;
                this.$api.updateUserPublicInfo({
                    nickname: this.userInfo.nickname
                }).then(res => {
                    console.log(res);
                    this.$globalData.userInfo.nickname = this.userInfo.nickname;
                })

            },
            savePassword() {
                if (!this.userPassword1 || !this.userPassword2) {
                    this.$message.error('密码为空！');
                } else if (this.userPassword2 === this.userPassword3) {
                    this.$api.updatePassword({
                        oldPassword: this.userPassword1,
                        newPassword: this.userPassword2
                    }).then(res => {
                        if (res.code === 200) {
                            this.userPasswordEdit = false;
                            this.$message({
                                message: '修改成功！',
                                type: 'success'
                            });
                            this.userPassword1 = '';
                            this.userPassword2 = '';
                            this.userPassword3 = '';
                        } else {
                            this.$message.error('旧密码错误，修改失败！');
                        }
                    })
                } else {
                    this.$message.error('两次输入的密码不一致！');
                }
            },
            finishEdit() {
                this.notUserNicknameEdit = true;
                this.userInfoDialogVisible = false;
                this.userPasswordEdit = false;
            },
            handleAddressChange(value) {
                console.log(value);
                this.addressInfo.provinceName = value[0];
                this.addressInfo.cityName = value[1];
                this.addressInfo.regionName = value[2];
            },
            getMyFavorite(){
                this.$api.getMyFavorite().then(res=>{
                    console.log('getMyFavorite 原始响应:', res);
                    if (res.code === 200){
                        const processedData = [];
                        // 处理每个收藏项
                        res.data.forEach(item => {
                            console.log('处理收藏项:', item);
                            const processedItem = {
                                id: item.productID,
                                imgUrl: item.images || '',
                                idleName: item.productName,
                                idleDetails: item.productDescription,
                                timeStr: item.createdAt.substring(0, 10) + " " + item.createdAt.substring(11, 19),
                                productPrice: item.productPrice, // 添加这个字段用于模板显示
                                statusSold: item.statusSold,
                                statusCheck: item.statusCheck,
                                favoriteCount: item.favoriteCount
                            };
                            console.log('处理后的项:', processedItem);
                            processedData.push(processedItem);
                        });
                        console.log('更新后的收藏列表:', processedData);
                        // 使用 Vue.set 确保数据响应性
                        this.$set(this.dataList, 2, processedData);
                    } else {
                        this.$message.error(res.message || '获取收藏列表失败');
                    }
                }).catch(err => {
                    console.error('获取收藏列表失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                });
            },
            getMySoldIdle(){
                this.$api.getMySoldOrders().then(res=>{
                    if (res.code === 200){
                        console.log('getMySoldOrders response:', res.data);
                        // 确保 dataList[3] 是一个数组
                        if (!this.dataList[3]) {
                            this.$set(this.dataList, 3, []);
                        }
                        // 对订单按创建时间倒序排序，确保最新订单在前面
                        const sortedOrders = res.data.sort((a, b) => {
                            return new Date(b.createdAt) - new Date(a.createdAt);
                        });

                        // 直接使用订单数据
                        this.dataList[3] = sortedOrders.map(order => {
                            // 处理图片URL
                            let imageUrl = '';
                            if (order.images) {
                                // 如果images是字符串（逗号分隔的URL），转换为数组
                                const imageArray = typeof order.images === 'string' ? 
                                    order.images.split(',') : 
                                    Array.isArray(order.images) ? order.images : [];
                                
                                // 获取第一个非空的图片URL
                                imageUrl = imageArray.find(url => url && url.trim()) || '';
                            }
                            // 如果order.product存在且有图片，作为备选
                            if (!imageUrl && order.product && order.product.images) {
                                const productImages = typeof order.product.images === 'string' ?
                                    order.product.images.split(',') :
                                    Array.isArray(order.product.images) ? order.product.images : [];
                                imageUrl = productImages.find(url => url && url.trim()) || '';
                            }

                            return {
                                id: order.orderId,
                                imgUrl: imageUrl,  // 使用处理后的图片URL
                                idleName: order.product ? order.product.productName : `订单 #${order.orderId}`,  // 优先使用商品名称
                                idleDetails: order.product ? order.product.description : (order.description || ''),
                                timeStr: order.createdAt ? 
                                    `${order.createdAt.substring(0, 10)} ${order.createdAt.substring(11, 19)}` : '',
                                productPrice: order.totalPrice || 0,
                                orderStatus: order.orderStatus || 0
                            };
                        });
                    } else {
                        console.error('获取已售出商品列表失败:', res);
                        this.$message.error(res.message || '获取已售出商品列表失败');
                    }
                }).catch(err => {
                    console.error('获取已售出商品列表失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                });
            },
            getMyOrder() {
                this.$api.getMyOrders().then(res => {
                    if (res.code === 200) {
                        console.log('获取到的订单数据:', res.data);
                        if (!this.dataList[4]) {
                            this.$set(this.dataList, 4, []);
                        }
                        const sortedOrders = res.data.sort((a, b) => 
                            new Date(b.createdAt) - new Date(a.createdAt)
                        );

                        // 修改点：添加图片处理逻辑
                        this.dataList[4] = sortedOrders.map(order => {
                            // 处理图片URL
                            let imageUrl = '';
                            
                            // 1. 优先从订单的images字段获取
                            if (order.images) {
                                const imageArray = typeof order.images === 'string' 
                                    ? order.images.split(',') 
                                    : Array.isArray(order.images) 
                                        ? order.images 
                                        : [];
                                imageUrl = imageArray.find(url => url && url.trim()) || '';
                            }
                            
                            // 2. 次优先从关联商品product中获取
                            if (!imageUrl && order.product && order.product.images) {
                                const productImages = typeof order.product.images === 'string'
                                    ? order.product.images.split(',')
                                    : Array.isArray(order.product.images) 
                                        ? order.product.images 
                                        : [];
                                imageUrl = productImages.find(url => url && url.trim()) || '';
                            }

                            return {
                                id: order.orderId,
                                imgUrl: imageUrl,  // 使用处理后的图片URL
                                idleName: order.product 
                                    ? order.product.productName 
                                    : `订单 #${order.orderId}`,
                                idleDetails: order.description || '',
                                timeStr: order.createdAt 
                                    ? `${order.createdAt.substring(0, 10)} ${order.createdAt.substring(11, 19)}` 
                                    : '',
                                productPrice: order.totalPrice || 0,
                                orderStatus: order.orderStatus || 0
                            };
                        });

                        console.log('处理后的订单列表:', this.dataList[4]);
                    } else {
                        console.error('获取订单列表失败:', res);
                        this.$message.error(res.message || '获取订单列表失败');
                    }
                }).catch(err => {
                    console.error('获取订单列表失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                });
            },
            getIdleItemData() {
                this.$api.getAllIdleItem().then(res => {
                    console.log(res);
                    if (res.status_code === 1) {
                        for (let i = 0; i < res.data.length; i++) {
                            res.data[i].timeStr = res.data[i].releaseTime.substring(0, 10) + " " + res.data[i].releaseTime.substring(11, 19);
                            let pictureList = JSON.parse(res.data[i].pictureList);
                            res.data[i].imgUrl = pictureList.length > 0 ? pictureList[0] : '';
                            if (res.data[i].idleStatus === 1) {
                                this.dataList[0].push(res.data[i]);
                            } else if (res.data[i].idleStatus === 2) {
                                this.dataList[1].push(res.data[i]);
                            }
                        }
                    }
                })
            },

            getAddressData() {
                this.$api.getAddress().then(res => {
                    if (res.code === 200) {
                        let data = res.data;
                        for (let i = 0; i < data.length; i++) {
                            data[i].detailAddressText = data[i].provinceName + data[i].cityName + data[i].regionName + data[i].detailAddress;
                            data[i].defaultAddress = data[i].defaultFlag ? '默认地址' : '设为默认';
                        }
                        console.log(data);
                        this.addressData = data;

                        // 存默认地址到localStorage，方便跨页面调用
                        const defaultAddr = data.find(item => item.defaultFlag === true);
                        if (defaultAddr) {
                            localStorage.setItem('defaultAddress', JSON.stringify(defaultAddr));
                        } else {
                            localStorage.removeItem('defaultAddress');
                        }
                    }
                })
            },
            handleEdit(index, row) {
                console.log(index, row);
                this.addressInfo = JSON.parse(JSON.stringify(row));
                this.selectedOptions = ['', '', ''];
                this.selectedOptions[0] = row.provinceName;
                this.selectedOptions[1] = row.cityName;
                this.selectedOptions[2] = row.regionName;
            },
            handleDelete(index, row) {
                console.log(index, row);
                this.$confirm('是否确定删除该地址?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$api.deleteAddress(row).then(res => {
                        if (res.code === 200) {
                            this.$message({
                                message: '删除成功！',
                                type: 'success'
                            });
                            this.addressData.splice(index, 1);
                            if (row.defaultFlag && this.addressData.length > 0) {
                                this.addressData[0].defaultFlag = true;
                                this.addressData[0].defaultAddress = '默认地址';
                                this.update({
                                    id: this.addressData[0].id,
                                    defaultFlag: true
                                });
                            }
                        } else {
                            this.$message.error('系统异常，删除失败！')
                        }
                    }).catch(() => {
                        this.$message.error('网络异常！')
                    });
                }).catch(() => {
                });

            },
            handleSetDefault(index, row) {
                console.log(index, row);
                row.defaultFlag = true;
                this.update(row);
            },
            fileHandleSuccess(response, file, fileList) {
                let imgUrl = response.data;

                this.imgFileList = [];

                this.$api.updateUserPublicInfo({
                    avatar: imgUrl,
                    nickname: this.userInfo.nickname,
                    userName: this.userInfo.userName,
                }).then(res => {
                    // 加时间戳防缓存
                    const updatedAvatar = imgUrl + '?t=' + new Date().getTime();

                    // 重新赋值整个对象以触发响应式更新
                    this.userInfo = {
                        ...this.userInfo,
                        avatar: updatedAvatar
                    };
                    this.$globalData.userInfo.avatar = updatedAvatar;

                    console.log("头像更新成功");
                }).catch(err => {
                    console.error("头像更新失败", err);
                });
            },
            update(data) {
                this.$api.updateAddress(data).then(res => {
                    if (res.code === 200) {
                        this.getAddressData();
                        this.$message({
                            message: '修改成功！',
                            type: 'success'
                        });
                    } else {
                        this.$message.error('系统异常，修改失败！')
                    }
                }).catch(() => {
                    this.$message.error('网络异常！')
                })
            },
            saveAddress() {
                if (this.addressInfo.id) {
                    console.log('update:', this.addressInfo);
                    this.update(this.addressInfo);
                    this.addressInfo = {
                        consigneeName: '',
                        consigneePhone: '',
                        provinceName: '',
                        cityName: '',
                        regionName: '',
                        detailAddress: '',
                        defaultFlag: false
                    };
                    this.selectedOptions = [];
                } else {
                    if (this.addressData.length >= 5) {
                        this.$message.error('已达到最大地址数量！')
                    } else {
                        console.log(this.addressInfo);
                        this.$api.addAddress(this.addressInfo).then(res => {
                            if (res.code === 200) {
                                this.getAddressData();
                                this.$message({
                                    message: '新增成功！',
                                    type: 'success'
                                });
                                this.selectedOptions = [];
                                this.addressInfo = {
                                    consigneeName: '',
                                    consigneePhone: '',
                                    provinceName: '',
                                    cityName: '',
                                    regionName: '',
                                    detailAddress: '',
                                    defaultFlag: false
                                };
                            } else {
                                this.$message.error('系统异常，新增失败！')
                            }
                        }).catch(e => {
                            this.$message.error('网络异常！')
                        })
                    }
                }
            },
            // 获取关注
            getMyFollowings() {
                this.$api.getFollowings({ userId: this.userInfo.userId }).then(res => {
                    if (res.code === 200) {
                        const followings = res.data.map(user => ({
                            userId: user.userId,               // 保留 ID
                            idleName: user.nickname,           // 昵称
                            imgUrl: user.avatar,               // 头像
                            isFollowed: true                   // ✅ 添加 isFollowed 字段（默认关注）
                        }));
                        this.$set(this.dataList, 5, followings); // ✅ 确保响应式更新
                    }
                }).catch(err => {
                    console.error("获取关注失败：", err);
                    this.$message.error("获取关注列表失败");
                });
            },
            // 获取粉丝列表（dataList[6]）
            getMyFollowers() {
                this.$api.getFollowers({ userId: this.userInfo.userId })
                    .then(res => {
                        if (res.code === 200) {
                            const followers = res.data.map(user => ({
                                userId: user.userId,
                                idleName: user.nickname,
                                imgUrl: user.avatar,
                                isFollowed: user.isFollowed // ✅ 添加这个字段
                            }));
                            this.$set(this.dataList, 6, followers);
                        }
                    })
                    .catch(err => {
                        console.error("获取粉丝失败：", err);
                        this.$message.error("获取粉丝列表失败");
                    });
            },
            // 取消关注
            unfollowUser(userId) {
                if (!userId) {
                    this.$message.error("操作失败：用户ID无效");
                    return;
                }

                this.$api.unfollowUser(userId)
                    .then(res => {
                        if (res.code === 200) {
                            this.$message.success(res.data);

                            // ✅ 手动移除取消关注的用户
                            this.$set(this.dataList, 5, this.dataList[5].filter(user => user.userId !== userId));
                        } else {
                            this.$message.error(res.message || "取消关注失败");
                        }
                    })
                    .catch(err => {
                        this.$message.error(err.message || "请求失败，请稍后重试");
                    });
            },
            // 回关某人（更新粉丝列表中的 isFollowed 状态）
            followBack(userId) {
                if (!userId) {
                    this.$message.error("操作失败：用户ID无效");
                    return;
                }

                this.$api.followUser(userId)
                    .then(res => {
                        if (res.code === 200) {
                            this.$message.success(res.data || "已关注");

                            // ✅ 回关成功后，更新 dataList[6] 中该用户的 isFollowed 字段为 true
                            const updatedFans = this.dataList[6].map(user => {
                                if (user.userId === userId) {
                                    return { ...user, isFollowed: true };
                                }
                                return user;
                            });

                            this.$set(this.dataList, 6, updatedFans);
                        } else {
                            this.$message.error(res.message || "关注失败");
                        }
                    })
                    .catch(err => {
                        console.error("关注错误:", err);
                        this.$message.error("请求失败，请稍后重试");
                    });
            }
        }
    }
</script>

<style scoped>

    .user-info-details {
        display: flex;
        height: 140px;
        align-items: center;
        margin: 20px 40px;
    }

    .user-info-details-text {
        margin-left: 20px;
    }

    .user-info-details-text-nickname {
        font-size: 26px;
        font-weight: 600;
        margin: 10px 0;
    }

    .user-info-details-text-time {
        font-size: 14px;
        margin-bottom: 10px;
    }

    .user-info-details-text-edit {
        margin-top: 10px;
    }

    .user-info-details-text-edit .el-button {
        margin-right: 20px;
    }

    .user-info-details-text-edit .el-button:last-child {
        margin-right: 0;
    }

    .user-info-splace {
        display: none;
    }

    .idle-container {
        padding: 0 20px;
        background-color: #f5f7fa;
        min-height: calc(100vh - 300px);
    }

    .idle-container-list {
        min-height: 55vh;
        background-color: #fff;
        border-radius: 8px;
        margin-top: 10px;
        padding: 20px;
        box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    }

    .idle-container-list-item {
        cursor: pointer;
        border-bottom: 1px solid #ebeef5;
        padding: 20px 0;
        margin: 0 10px;
        transition: all 0.3s;
    }

    .idle-container-list-item:hover {
        background-color: #f5f7fa;
        transform: translateY(-2px);
    }

    .idle-container-list-item:last-child {
        border-bottom: none;
    }

    .idle-container-list-item-detile {
        height: 120px;
        display: flex;
        align-items: flex-start;
        padding: 0 10px;
    }

    .idle-container-list-item-text {
        margin-left: 20px;
        height: 120px;
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .idle-container-list-title {
        font-weight: 600;
        font-size: 18px;
        color: #303133;
        margin-bottom: 8px;
        display: flex;
        align-items: center;
    }

    .idle-container-list-title .el-tag {
        margin-left: 10px;
    }

    .idle-container-list-idle-details {
        font-size: 14px;
        color: #606266;
        line-height: 1.5;
        margin-bottom: 8px;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        overflow: hidden;
    }

    .idle-container-list-idle-time {
        font-size: 13px;
        color: #909399;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
    }

    .time-text {
        color: #909399;
    }

    .favorite-count {
        display: flex;
        align-items: center;
        color: #909399;
    }

    .favorite-count i {
        color: #ff9900;
        margin-right: 4px;
        font-size: 14px;
    }

    .idle-item-foot {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: auto;
    }

    .idle-price {
        font-size: 20px;
        color: #f56c6c;
        font-weight: bold;
    }

    .operation-buttons {
        display: flex;
        gap: 10px;
    }

    .image-slot {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #909399;
    }

    .image-slot i {
        font-size: 24px;
        margin-bottom: 8px;
    }

    .no-image-text {
        font-size: 14px;
        text-align: center;
    }

    .el-empty {
        padding: 40px 0;
    }

    .address-container {
        padding: 10px 20px;
    }

    .address-container-back {
        margin-bottom: 10px;
    }

    .address-container-add-title {
        font-size: 15px;
        color: #409EFF;
        padding: 10px;
    }

    .address-container-add-item {
        margin-bottom: 20px;
    }

    .demonstration {
        color: #666666;
        font-size: 14px;
        padding: 10px;
    }

    .address-container-add {
        padding: 0 200px;
    }

    .address-container-list {
        padding: 30px 100px;
    }

    .user-card {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 14px 20px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        background-color: #fff;
        margin-bottom: 12px;
    }

    .user-card-left {
        display: flex;
        align-items: center;
        gap: 14px;
    }

    .nickname {
        font-size: 16px;
        font-weight: 500;
    }

    .user-card-right .el-button {
        font-size: 14px;
        padding: 8px 20px;
    }


</style>
